import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: '',
    farmers: [],//包装列表
    orderObj: {},
    othenFeeList: [],//其他费用列表
    detailList: [],//选择出库列表
    name: '',
    showPriceInput: false,
    unitPrice: '',
    canNum: '',
    ids: '',
    newCropList: [],
    canWeight: '',
    disabled: false,
    baozhprice: 0,
    allMoney: 0,
    outStockStatus: 0,
		otherFee:0,
		priceInfo: {},
		totalData:{},
		packsData:[],//传递过来的包装列表
		nhData:[],//传递农户的包装列表
		farmProductPurchaseOrderId:'', //传递过来的采购单id
		settleHas:false
  },
  hideInput() {
    this.setData({
      showPriceInput: false,
      unitPrice: ''
    })

  },
	inputvalue(e){
			if(e.detail*1>this.data.canWeight*1){
				wx.showToast({
					title: '输入量不得大于可出库量',
					icon: 'none',
					duration: 2000
				})
			}
	},
  changemoney(e) {
    const serverPrice = "orderObj.serverPrice"
    this.setData({
      [serverPrice]: this.money(e.detail) 
    })
		this.addMoney()

  },
	//打印小票
	print(){
		let tips="是否打印小票？"
		if(this.data.type==2){
			tips="发货成功是否打印小票？"
		}
		Dialog.confirm({
			title: tips,
		})
			.then(() => {
				wx.$apis.printOutStock(this.data.orderObj.id).then(res => {
					wx.showToast({
						title: "操作成功",
						icon: 'none',
						duration: 2000
				})
					wx.setStorage({
						key: "back",
						data: true,
						success: function () {
								wx.navigateBack(); //返回上一个页面
						}
					})
				}).catch(err => {
					wx.hideLoading()
				})
			})
			.catch(() => {
						if(this.data.type==2){
						// wx.switchTab({
						// 	url: "/pages/order/index/index",
						// })
						wx.setStorage({
							key: "back",
							data: true,
							success: function () {
									wx.navigateBack(); //返回上一个页面
							}
						})
					}
			});

	},
  submit() {
		wx.showLoading({
      title: "操作中..."
    });
    let detailList = this.data.detailList.filter(item => item.checked);
    let newDetails = detailList.map(item => {
			if(this.data.type==1){
				return {
					enterStockOrderId: item.id,
					outStockWight: item.stockWeight * 1
				}
			}else{
				return {
					enterStockOrderId: item.enterStockOrderId,
					outStockWight: item.stockWeight * 1
				}
			}

    });
    let packs = this.data.farmers.map(item => {
      return {
        packId: item.packId,
        packNumber: item.num?item.num:0
      }
    });
		if (!this.data.farmers.length) {
      return wx.showToast({
        title: "请选择包装",
        icon: "error",
        duration: 1000
      });
    }
		if (!newDetails.length) {
      return wx.showToast({
        title: "请选择出库明细",
        icon: "error",
        duration: 1000
      });
    }
		if(this.data.type != 1){
			if (!this.data.orderObj.transactionPrice) {
				return wx.showToast({
					title: "请输入单价",
					icon: "error",
					duration: 1000
				});
			}
		}
    let api,tips;
		let other=this.data.othenFeeList.map(item=>{
			item.feePrice=wx.$getFen(item.feePrice*1)
			return item
		})
		
    let obj = {
      id: this.data.orderObj.id,
      otherFees:other,
      packs: packs,
      details: newDetails,
      serverPrice:wx.$getFen(this.data.orderObj.serverPrice),
    };
    if (this.data.type == 1) {
      api = 'workerChange';   //备货
			tips='备货成功'
    } else if (this.data.type == 2) {  
      api = 'fhmarketer'; //发货
			tips='发货成功';
			packs = this.data.farmers.map(item => {
				return {
					packId: item.packId,
					packNumber: item.num?item.num:0
				}
			});
      obj = {
				companyId:app.globalData.userInfo.companyData.companyId,
				cropId:this.data.orderObj.cropId,
				cropName:this.data.orderObj.cropName,
				demandWeight: this.data.orderObj.demandWeight,
				details: newDetails,
				farmProductPurchaseOrderId:this.data.farmProductPurchaseOrderId, //采购单ID
				packs:packs,
				serverPrice:wx.$getFen(this.data.orderObj.serverPrice),
				transactionPrice:wx.$getFen(this.data.orderObj.transactionPrice*1),
				otherFees:other,
      }
    } else if (this.data.type == 3) { 
      api='updateList';//修改
			tips='修改成功'
      obj = {
        ...obj,
        demandWeight: this.data.orderObj.demandWeight, //修改时需要传
				transactionPrice:wx.$getFen(this.data.orderObj.transactionPrice*1)
      }
    }
    wx.$apis[api](obj).then(res => {
			if(this.data.type==2){
				this.setData({
					"orderObj.id":res.data
				})
				this.print()
			}else{
				wx.showToast({
					title: tips,
					icon: "success",
					duration: 2000
				}).then(() => {
					setTimeout(() => {
						wx.setStorage({
							key: "back",
							data: true,
							success: function () {
									wx.navigateBack(); //返回上一个页面
							}
						})
					}, 1000);
				});
			}

    }).catch(err => {
      wx.hideLoading()
    })

  },
  cancelPrice() {
    this.hideInput();
  },
  // 添加物料确定
  submitPrice() {
    const ids = this.data.ids;
    const weight = "detailList[" + ids + "].stockWeight";
    this.setData({
      [weight]: this.data.unitPrice,
      showPriceInput: false
    })
		this.getPriceInfo()
		this.setData({
      unitPrice: ''
    })
  },
  toAddMaterial(e) {
    console.log(2, e)
    this.setData({
      ids: e.currentTarget.dataset.index,
      showPriceInput: true,
			canWeight:e.currentTarget.dataset.item.kkk
    })
  },
  onChange(event) {
    const index = event.currentTarget.dataset.index;
    let detailList = this.data.detailList;
    detailList[index].checked = !detailList[index].checked
		let newCropList = detailList.filter(item => item.checked)
    this.setData({
      detailList,
			newCropList
    })
	this.getPriceInfo()
  },
  //获取交易出库信息列表
  getInfoList(name,arr) {
			let obj= {
				current: 1,
				companyId: app.globalData.userInfo.companyData.companyId,
				cropName: name,
				size: 100,
			}
			if(arr){
				obj.farmerUserIds=arr
			}
			wx.$apis.getMarketList(obj).then(res => {
				let aaa=res.data&&res.data.records.filter(item=>{
					return item.stockWeight != 0
				}).map(item=>{
					item.kkk=item.stockWeight,
					item.enterStockOrderId=item.id,
					item.createTime=	item.createTime.replace('T',' ')
					item.farmerMobile=	wx.$getMobile(item.farmerMobile)
					return item 
				})
					this.setData({
						detailList: aaa,
					})
			}).catch(err => {
				wx.hideLoading()
			})

  },
	//
	getPriceInfo() {
		let newCropList = this.data.newCropList;
		if (newCropList && newCropList.length) {
				let settlementAmount = 0;
				newCropList.forEach(item => {
						settlementAmount += item.stockWeight*1
				});
				let priceInfo = {
						settlementAmount: settlementAmount,
						orderNumber: newCropList.length
				}
				this.setData({
						priceInfo: priceInfo,
				})
				this.addMoney()
				console.log(this.data.priceInfo,'合计=-=====')
		} else {
				this.setData({
						priceInfo: {}
				})
				this.addMoney()
		}
},

  onClose(event) {
    const valueId = event.currentTarget.dataset.id
    const { position, instance } = event.detail;
    switch (position) {
      case 'right':
        Dialog.confirm({
          message: '确定删除吗？',
        }).then(() => {
          instance.close();
          let valueList = this.data.farmers;
          valueList.splice(valueList.findIndex(v => v.id === valueId), 1)
          this.setData({
            farmers: valueList
          })
          let total = this.countTotal(this.data.farmers, 'price', 'num')
          this.setData({
            baozhprice: total
          })
        });
        break;
    }
  },
  onCloseFee(event) {
    const name = event.currentTarget.dataset.name
    const { position, instance } = event.detail;
    switch (position) {
      case 'right':
        Dialog.confirm({
          message: '确定删除吗？',
        }).then(() => {
          instance.close();
          let valueList = this.data.othenFeeList;
          valueList.splice(valueList.findIndex(v => v.feeName === name), 1)
          this.setData({
            othenFeeList: valueList
          })
					this.setData({
						otherFee:	this.countAddFee(this.data.othenFeeList, 'feePrice')
          })
					this.addMoney()
        });
        break;
    }
  },

  addfee() {
    wx.navigateTo({
      url: "/pages/order/addfee/addfee"
    });
  },
  //修改需求数量
  onChangenum(e) {
    // console.log(e, '1')
    const demandWeight = 'orderObj.demandWeight'
    this.setData({
      [demandWeight]: e.detail
    })
  },
	//修改单价
	onChangeMoney(e) {
    // console.log(e, '1')
    const transactionPrice = 'orderObj.transactionPrice'
    this.setData({
      [transactionPrice]:this.money(e.detail) 
    })
		this.addMoney()
  },
	money(val) {
		let num = val.toString(); //先转换成字符串类型
		if (num.indexOf('.') == 0) { //第一位就是 .
			num = '0' + num
		}
		num = num.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
		num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
		num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
		num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
		if (num.indexOf(".") < 0 && num != "") {
			num = parseFloat(num);
		}
		return num
	},
	//方法
	getNewList(parmas){
		var temp={};
		for(var i in parmas){
			var key =parmas[i].packId;
			if(temp[key]){
				temp[key].packId=parmas[i].packId;
				temp[key].num +=parmas[i].num;
				temp[key].name =parmas[i].name;
				temp[key].price =parmas[i].price;
				temp[key].spec =parmas[i].spec;
				temp[key].inventory =parmas[i].inventory;
				temp[key].checked=true;
				
			}else{
				temp[key]={};
				temp[key].packId=parmas[i].packId;
				temp[key].num =parmas[i].num;
				temp[key].name =parmas[i].name;
				temp[key].price =parmas[i].price;
				temp[key].spec =parmas[i].spec;
				temp[key].inventory =parmas[i].inventory;
				temp[key].checked=true;
			}
		}
		var newArry=[];
		for(var k in temp){
			newArry.push(temp[k]);
		}
		return newArry

	},
  //备货单详情
  getDetail(id) {
    wx.$apis.getOutInfo(id).then(res => {
      let data = res.data
				let	farmers = res.data.packs.map(item => {
					return {
						packId: item.packId,
						name: item.packName,
						num: item.packNumber,
						price:wx.$getYuan(item.packPrice),
						spec: item.packSpecification,
						inventory:item.inventory
					}
				})
			farmers=this.getNewList(farmers)
      data.details.map((item, i) => {
        item.checked = true;
				item.kkk=item.stockWeight*1+item.outStockWight*1;
				item.stockWeight=item.outStockWight;
				item.createTime=item.createTime.replace('T',' ')
      })
			data.otherFees.map((item, i) => {
        item.feePrice = wx.$getYuan(item.feePrice);
      })
      data.goodsOwnerMobile = wx.$getMobile(data.goodsOwnerMobile)
      this.setData({
        orderObj: data,
				allMoney:data.countPrice?wx.$getYuan(data.countPrice):0,
				'orderObj.createTime':data.createTime.replace('T',' '),
				'orderObj.serverPrice':data.serverPrice? wx.$getYuan(data.serverPrice):0,
				'orderObj.packPrice':data.packPrice? wx.$getYuan(data.packPrice):0,
        name: data.cropName,
				packsData:farmers,
        farmers,
        othenFeeList: data.otherFees,
        outStockStatus: res.data.outStockStatus,
				newCropList: res.data.details,
				detailList: res.data.details,
      })
			if(data.transactionPrice){
				this.setData({
				'orderObj.transactionPrice': wx.$getYuan(data.transactionPrice),
				})
			}
			if(this.data.farmers==null){
				this.setData({
					baozhprice:0
				})
			}else{
				let total = this.countTotal(this.data.farmers, 'price', 'num')
				this.setData({
					baozhprice: total?total:0
				})
			}
			this.getPriceInfo()
    }).catch(err => {
      wx.hideLoading()
    })
  },
	//添加包装
	addpick() {
			wx.navigateTo({
				url: "/pages/order/choosepackage/choosepackage?pack=1&type="+this.data.type,
				success: (res) => {
					res.eventChannel.emit('packListData', {
								farmers:this.data.packsData,
					})
				}
			})
		},
  //计算表单数量方法
  countTotal(arr, keyName, unit) {
    let $total = 0;
    $total = arr.reduce(function (total, currentValue, currentIndex, arr) {
      return currentValue[keyName] ? (total + currentValue[keyName] * currentValue[unit]) : total;
    }, 0);
    return $total;
  },
	//计算其他费用的总和
	countAddFee(arr, keyName){
		let $total = 0;
    $total = arr.reduce(function (total, currentValue) {
      return currentValue[keyName] ? (total + currentValue[keyName]*1) : total;
    }, 0);
    return $total;
	},
  //计算合计
  addMoney() {
		if(this.data.orderObj.transactionPrice&&this.data.priceInfo.settlementAmount){  //有单价和总净重
			let all;
			if(this.data.orderObj.serverPrice){
			 all = this.data.orderObj.serverPrice * 1 + this.data.baozhprice+this.countAddFee(this.data.othenFeeList, 'feePrice') +this.data.orderObj.transactionPrice*this.data.priceInfo.settlementAmount*1
			}else{
			 all = this.data.baozhprice+this.countAddFee(this.data.othenFeeList, 'feePrice') +this.data.orderObj.transactionPrice*this.data.priceInfo.settlementAmount*1
			}
			this.setData({
				allMoney: wx.$getPrice(all)?wx.$getPrice(all):0
			})
		}else{
			let all;
			if(this.data.orderObj.serverPrice){
				 all = this.data.orderObj.serverPrice * 1 + this.data.baozhprice+this.countAddFee(this.data.othenFeeList, 'feePrice')
			}else{
			 all =this.data.baozhprice+this.countAddFee(this.data.othenFeeList, 'feePrice')
			}
			this.setData({
				allMoney: wx.$getPrice(all)?wx.$getPrice(all):0
			})
		}

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const id = options.id
    const type = options.type
    const settleHas = options.settleHas
    this.setData({
      id,
      type,
			settleHas
    })
		if(this.data.type==3){
			this.getDetail(this.data.id)
		}
		console.log('类型',this.data.type)
		const eventChannel = this.getOpenerEventChannel()
		eventChannel.on('famarListData', (data) => {
			this.setData({
				totalData: data.totalData, //作物信息
				farmProductPurchaseOrderId:id,//订单id
				// id:data.id,
				// farmers:data.totalData.packs,  //页面有返回包装
				'orderObj.cropName':data.totalData.cropName,
				'orderObj.demandWeight':data.totalData.demandWeight,
				'orderObj.cropId':data.totalData.cropId,
				packsData:data.packsData,//包装信息
				nhData:data.nhData,// 农户信息
				'orderObj.goodsOwnerName':data.hzInfo.goodsOwnerName,
				'orderObj.goodsOwnerMobile':data.hzInfo.goodsOwnerMobile,
			})
			if(this.data.nhData==null){
				this.getInfoList(this.data.orderObj.cropName);
			}else{
				this.getInfoList(this.data.orderObj.cropName,this.data.nhData);
			}
	})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.addMoney()

    wx.getStorage({
      key: 'packageType',
      success: (res) => {
        let typeList = res.data.packageTypeList
        if (typeList && typeList.length) {
					typeList.forEach(item=>{
						if(this.data.type==3){
							item.packId=item.packId

						}else{
							item.packId=item.id

						}
					})
          this.setData({
            farmers: typeList,
          })
          let total = this.countTotal(this.data.farmers, 'price', 'num')
          this.setData({
            baozhprice: total?total:0
          })
				this.addMoney()
        }
        wx.removeStorage({
          key: 'packageType',
        })
      }
    })
    wx.getStorage({
      key: 'feeData',
      success: (res) => {
        let othenFeeList = this.data.othenFeeList
        othenFeeList.push(res.data)
        this.setData({
          othenFeeList: othenFeeList
        })
				this.setData({
						otherFee:	this.countAddFee(this.data.othenFeeList, 'feePrice')
				})
				this.addMoney()
        wx.removeStorage({
          key: 'feeData',
        })
      }
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})